package com.huaqin.customer;

import java.util.ArrayList;
import java.util.List;

import android.util.Log;

import com.huaqin.common.Featrue;
import com.huaqin.expression.ExpressionEvaluator;
import com.huaqin.salestracker.SalesTrackerService;

public class Trigger {

	public static final String ALLOWED_STRING = " ()!truefalse|&"; //Logical string of characters may appear
	public static final String TAG = "Trigger";
	private final static String CONDITION_PAGAGE_NAME = "com.huaqin.customer.expansion";
	private String mLogicString = null; //Thelogic string of trigger by Configure
	private String mResultString = null; //To be  the result of the operation  logic string
//	private Context mContext = null;
	
	private List<ConditionInterface> mConditions = null;
	private List<Boolean> mResult = null;

	public Trigger(){
		mConditions = new ArrayList<ConditionInterface>();
		mResult = new ArrayList<Boolean>();
//		mContext = SalesTrackerService.mContext;
	}
	
	//add condition
	public boolean addCondition(String className, String key, String operator, String values){
	    boolean ret = false;
		
		Log.v(TAG, "className:" + className + " key: " + key + " operator:" + operator + " values:" + values);
		
		if (className == null || key == null || operator == null || values == null) {
			Log.e(TAG, "addCondition(): Incoming  parameter is empty");
		}
		else{
		    ConditionInterface condition = createConfitionInstance(className);
    		if(condition != null){
    			condition.setParam(key, operator, values);
    			mConditions.add(condition);
    			mResult.add(false);
    			ret = true;
    		}
		}
		
		return ret;
	}
	
	//Get current condition list instance
	public List<ConditionInterface> getCondition(){
		return mConditions;
	}
	
	//Set Logical string of Tigger 
	public boolean setTigger(String str){
		
		if(str == null){
			Log.e(TAG,"set Address ==> address is null");
			return false;
		}

		mLogicString = str;
		return true;
	}

	public boolean updateAllkCondition(){
		Log.v(TAG,"check all condition");
		
		if(mConditions.isEmpty())
			return false;
		
		int length = mConditions.size();
		for(int index = 0; index < length; index++){
			updateCondition(index);
		}

		return getLogicStringResult();
	}
	
	public void finishAllCondition(){
		int length = mConditions.size();
		for(int index = 0; index < length; index++){
			finishCondition(index);
		}
	}
	
	public String getConditionDescription(){
	    int length = mConditions.size();
	    String description = "";
        for(int index = 0; index < length; index++){
            String tmep = getDesctiption(index); 
            if(index != 0 && tmep != null){
                description += "\n----------------------------\n";
            }
            description += tmep;
        }
        return description;
	}

	//检查当前逻辑值的返回结果,将逻辑字符串中的各个逻辑值填入
	public boolean getLogicStringResult(){

		try {
			FillingResult2LogicString(); //匹配出错停止运行
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Log.v(TAG, "==> LogicStringResult: " + mResultString);
		return (Boolean)ExpressionEvaluator.evaluate(mResultString);
	}
	
	private ConditionInterface createConfitionInstance(String className){
		
		String targetClassName =  CONDITION_PAGAGE_NAME + "." + className;
		ConditionInterface condition = null;
		try{
			condition = ((ConditionInterface) (Class.forName(targetClassName).newInstance()));
  		} catch (Exception e) {
			Log.e(TAG, "Create Condition Failed!");
 		}
		
		return condition;
	}
	
	//将结果依次填入逻辑字符串中
	private boolean FillingResult2LogicString() throws Exception{
		if (mLogicString == null || mResult == null || mResult.isEmpty()){
			
			Log.e(TAG,  "mLogicString is null or mResult is empty!");
			return false;
		}
		
		mResultString = String.format(mLogicString, mResult.toArray());

		if(Featrue.isDebug)
			Log.i(TAG,  "ResultString[" + mResultString + "]");
		
		return true;
	}
	
	//检查逻辑字符的合法性
	public boolean isValidLogicString(String source){
		if(source == null){
			return false;
		}
        int index = 0;
        while(index < source.length()){
            if(ALLOWED_STRING.indexOf(source.charAt(index++)) == -1){
                return false;
            }
        }
        return true;
	}

	//指定条件执行并返回当前结果
	@SuppressWarnings(value = { })
	private boolean updateCondition(int index){
		boolean result = false;
		
		if(mConditions.isEmpty())
			return false;
	
		ConditionInterface targetCondition = mConditions.get(index);

		result = targetCondition.getResult();
		if(result){
			updateConditionResult(index, true);
		}
		else{
			targetCondition.execute();
			updateConditionResult(index, false);
		}

		if(Featrue.isDebug)
			Log.i(TAG,  "update Current Condition Result[" + result + "]");

		return result;
	}
	
	private String getDesctiption(int index){
	    String description = null;
	    if(!mConditions.isEmpty()){
            ConditionInterface targetCondition = mConditions.get(index);
            description=  targetCondition.getKeyDescription();
        }
	    return description;
	}
	
	private void finishCondition(int index){
		if(!mConditions.isEmpty()){
		    ConditionInterface targetCondition = mConditions.get(index);
	        targetCondition.finish();
		}
	}

	private void updateConditionResult(int index, boolean bool ){
		mResult.set(index, bool);
	}
}
